#pragma once
#include <iostream>
#include <cstring>
#include <functional>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/wait.h>
#include <pthread.h>
#include <memory>
#include "Log.hpp"
#include "InetAddr.hpp"

class Socket;
using SockPtr = std::shared_ptr<Socket>;

static const int gbacklog=8;

enum
{
    SOCK_ERROR = 1,
    BIND_ERROR,
    LISTEN_ERROR
};

class Socket
{
public:
    virtual void CreateSocketOrDie() = 0;
    virtual void CreateBindOrDie(uint16_t port) = 0;
    virtual void CreateListenOrDie(int backlog=gbacklog) = 0;
    virtual SockPtr Accepter(InetAddr *addr) = 0;
    virtual bool Connector(const std::string &peerip, uint16_t peerport) = 0;
    virtual int Sockfd() = 0;
    virtual void Close() = 0;
    virtual ssize_t Recv(std::string *out) = 0;
    virtual ssize_t Send(std::string &in) = 0;

    void BuildListenSocket(uint16_t port)
    {
        CreateSocketOrDie();
        CreateBindOrDie(port);
        CreateListenOrDie(gbacklog);
    }

    bool BuildClientSocket(const std::string &peerip,uint16_t peerport)
    {
        CreateSocketOrDie();
        return Connector(peerip,peerport);
    }
};

class TcpSocket : public Socket
{
public:
    TcpSocket() {}
    TcpSocket(int sockfd) : _sockfd(sockfd) {}

    virtual void CreateSocketOrDie() override
    {
        _sockfd = socket(AF_INET, SOCK_STREAM, 0);
        if (_sockfd < 0)
        {
            LOG(FATAL, "socket create error\n");
            exit(SOCK_ERROR);
        }
        LOG(INFO, "socket create success,sockfd:%d\n", _sockfd);
    }

    virtual void CreateBindOrDie(uint16_t port) override
    {
        sockaddr_in local;
        memset(&local, 0, sizeof(local));
        local.sin_family = AF_INET;
        local.sin_port = htons(port);
        local.sin_addr.s_addr = INADDR_ANY;

        if (bind(_sockfd, (struct sockaddr *)&local, sizeof(local)) < 0)
        {
            LOG(FATAL, "bind error\n");
            exit(BIND_ERROR);
        }
        LOG(INFO, "bind create success\n");
    }

    virtual void CreateListenOrDie(int backlog) override
    {
        if (listen(_sockfd, backlog) < 0)
        {
            LOG(FATAL, "listen error\n");
            exit(LISTEN_ERROR);
        }
        LOG(INFO, "listen create success\n");
    }

    virtual SockPtr Accepter(InetAddr *cliaddr) override
    {
        struct sockaddr_in client;
        socklen_t len = sizeof(client);
        int sockfd = accept(_sockfd, (struct sockaddr *)&client, &len);
        if (sockfd < 0)
        {
            LOG(WARNING, "accept error\n");
            return nullptr;
        }
        *cliaddr = InetAddr(client);
        LOG(INFO, "get a new link,client info: %s, sockfd is: %d\n", cliaddr->AddrStc().c_str(), sockfd);

        return std::make_shared<TcpSocket>(sockfd);
    }

    virtual bool Connector(const std::string &peerip, uint16_t peerport) override
    {
        struct sockaddr_in server;
        memset(&server, 0, sizeof(server));
        server.sin_family = AF_INET;
        server.sin_port = htons(peerport);
        inet_pton(AF_INET, peerip.c_str(), &server.sin_addr);

        int n = connect(_sockfd, (struct sockaddr *)&server, sizeof(server));
        if (n < 0)
        {
            return false;
        }
        return true;
    }

    virtual int Sockfd() override
    {
        return _sockfd;
    }

    virtual void Close() override
    {
        close(_sockfd);
    }

    virtual ssize_t Recv(std::string *out) override
    {
        char buffer[4096];
        ssize_t n = recv(_sockfd, buffer, sizeof(buffer) - 1, 0);
        if (n > 0)
        {
            buffer[n] = 0;
            *out += buffer;
        }
        return n;
    }

    virtual ssize_t Send(std::string &in) override
    {
        return send(_sockfd, in.c_str(), in.size(), 0);
    }

private:
    int _sockfd; // 可以是listensockfd，也可以是普通sockfd
};